using System;
using System.Linq;
using System.IO;

namespace Kiwi.Node.Utility
{
    public static class PathHelper
    {
        public static string ResolvePath(string homeFolder, string baseName, params string[] fallbackExtensions)
        {
            var normalizedName = string.Join("\\", baseName.Split('/')
                                                       .Select(s => s.Replace('\\', '/')));

            var basePath = Path.Combine(homeFolder, normalizedName);

            return TryFindFile(basePath,
                               p => p,
                               p => p + ".js",
                               p => p + ".node");

        }

        private static string TryFindFile(string basePath, params Func<string, string>[] variations)
        {
            return (from v in variations
                    let p = v(basePath)
                    where File.Exists(p)
                    select p).FirstOrDefault();
        }
    }
}